package edu.lingnan.store.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import edu.lingnan.store.common.ResultBean;
import edu.lingnan.store.entity.User;
import edu.lingnan.store.service.RoleService;
import edu.lingnan.store.service.UserService;
import edu.lingnan.store.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2021-01-28 16:57:07
 */
@RestController
@RequestMapping("user")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    /**
     * 登录
     * @param user
     * @return
     */
    @PostMapping("login")
    public ResultBean login(@RequestBody User user){
        String loginAccount = user.getLoginAccount();
        ResultBean resultBean = new ResultBean<>();
        Map<String,Object> map = new HashMap<>();
        if(user==null){
            resultBean.setSuccess(false);
            return resultBean;
        }
        //判断是邮箱还是手机号的正则表达式
        String em = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
        String ph = "^[1][34578]\\d{9}$";
        if(loginAccount.matches(em)){
            user.setEmail(loginAccount);
        }else if(loginAccount.matches(ph)){
            user.setContact(loginAccount);
        }else{
            user.setLoginName(loginAccount);
        }
        resultBean = userService.login(user);
        if(resultBean.isSuccess()){
            //更新
            user = (User) resultBean.getData();
            user.setLastLoginTime(new Date());
            userService.update(user);
            map.put("user",resultBean.getData());
            //获取token
            String token = jwtTokenUtil.generateToken(user);
            String tokenHead = jwtTokenUtil.getTokenHead();
            map.put("token",token);
            map.put("tokenHead",tokenHead);
            resultBean.setData(map);
        }
        return resultBean;
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @PostMapping("register")
    public ResultBean<User> register(User user){
        ResultBean<User> resultBean = new ResultBean<>();
        if(user==null){
            resultBean.setSuccess(false);
            return resultBean;
        }
        if(userService.checkUserExist(user).size()>0){
            resultBean.setSuccess(false);
            resultBean.setMsg("此邮箱或手机号已被注册！");
            return resultBean;
        }
        user.setCreateTime(new Date());
        user.setStatus("NORMAL");
        user.setIntegral(0);
        resultBean.setSuccess(userService.insert(user)>0);
        resultBean.setData(user);
        return resultBean;
    }

    /**
     * 登出
     * @return
     */
    @GetMapping("loginOut")
    public ResultBean loginOut(){
        //前端删除token
        return new ResultBean("登出成功！",true,null);
    }

    @GetMapping("getIntegral")
    public ResultBean getIntegral(Integer userId){
        //前端删除token
        Integer integral = userService.getUserIntegral(userId);
        return new ResultBean("",true,integral);
    }

    /**
     * 刷新token
     * @param map
     * @return
     */
    @PostMapping("refreshToken")
    public ResultBean refreshToken(@RequestBody HashMap<String, String> map){
        String refreshToken = jwtTokenUtil.refreshHeadToken(map.get("token"));
        if (refreshToken == null) {
            return new ResultBean("token已过期！",false,null);
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshToken);
        tokenMap.put("tokenHead", tokenHead);
        return new ResultBean("刷新成功！",true,tokenMap);
    }

    /**
     * 获取登录用户信息
     * @return
     */
    @PostMapping("info")
    public ResultBean info(@RequestBody HashMap<String, Object> map){
        if(map.get("userId")==null){
            return new ResultBean("请登录后操作！",false,null);
        }
        User user = userService.queryById(Integer.parseInt(map.get("userId").toString()));
        map.put("userName",user.getLoginName());
        map.put("icon",user.getLoginName().substring(0,1).toLowerCase());
        map.put("menus", roleService.getMenuList(user.getId()));
        ResultBean resultBean = new ResultBean<>();
        resultBean.setData(map);
        return resultBean;
    }

    /**
     * 根据条件查询用户数据
     * @param page
     * @param limit
     * @param bean
     * @return
     */
    @GetMapping("list")
    public ResultBean getUserData(Integer page, Integer limit, String bean){
        ResultBean resultBean = new ResultBean<>();
        User user = JSONUtil.toBean(bean,User.class);
        IPage<User> iPage = userService.queryAllByLimit(page,limit,user);
        Map<String, Object> map = new HashMap<>();
        map.put("total",iPage.getTotal());
        map.put("data",iPage.getRecords());
        resultBean.setData(map);
        resultBean.setMsg("操作成功！");
        return resultBean;
    }

    @GetMapping("noRoleUsers")
    public ResultBean getNoRoleUsers(){
        ResultBean resultBean = new ResultBean<>();
        List<User> list = userService.getNoRoleUsers();
        resultBean.setData(list);
        return resultBean;
    }

    /**
     * 获取指定用户信息
     * @param id
     * @return
     */
    @GetMapping("userInfo")
    public ResultBean getUserInfo(@RequestParam("id")  Integer id){
        ResultBean<User> resultBean = new ResultBean<>();
        if(id == null || id < 0){
            resultBean.setSuccess(false);
            return resultBean;
        }
        User user = userService.queryById(id);
        if(user!=null){
            resultBean.setData(user);
        }
        return resultBean;
    }

    /**
     * 修改用户信息
     * @param bean
     * @return
     */
    @PostMapping("save")
    public ResultBean updateUser(@RequestBody User bean){
        ResultBean<User> resultBean = new ResultBean<>();
        boolean result = false;
        if(bean.getId()!=null && bean.getId()>0){
            result = userService.update(bean)>0;
        }else{
            bean.setStatus("NORMAL");
            result = userService.insert(bean)>0;
        }
        if(!result){
            resultBean.setSuccess(false);
            resultBean.setMsg("保存失败！");
            return resultBean;
        }
        resultBean.setMsg("保存成功！");
        return resultBean;
    }

    /**
     * 修改用户信息
     * @param bean
     * @return
     */
    @PostMapping("resetPassword")
    public ResultBean resetPassword(@RequestBody User bean){
        ResultBean<User> resultBean = new ResultBean<>();
        boolean result = true;
        //验证邮箱账号
        List<User> users = userService.checkUserRight(bean);
        if(users.isEmpty()){
            resultBean.setSuccess(false);
            resultBean.setMsg("邮箱或账号不正确/不存在！");
            return resultBean;
        }
        bean.setId(users.get(0).getId());
        result = userService.update(bean)>0;
        if(!result){
            resultBean.setSuccess(false);
            resultBean.setMsg("重置失败！");
            return resultBean;
        }
        resultBean.setMsg("重置成功！");
        return resultBean;
    }

    /**
     * 批量修改状态
     * @param ids
     * @return
     */
    @PostMapping("updateStatus")
    public ResultBean updateStatus(Integer[] ids,String status){
        ResultBean<User> resultBean = new ResultBean<>();
        if( ids == null || ids.length == 0){
            resultBean.setSuccess(false);
            resultBean.setMsg("请选择需要修改的数据！");
            return resultBean;
        }
        resultBean.setSuccess(userService.changeUserStatus(ids,status)>0);
        if(!resultBean.isSuccess()){
            resultBean.setMsg("修改失败！");
            return resultBean;
        }
        resultBean.setMsg("修改成功！");
        return resultBean;
    }

    @PostMapping("delete")
    public ResultBean delete(Integer id){
        ResultBean resultBean = new ResultBean<>();
        resultBean.setSuccess(userService.deleteById(id));
        if(!resultBean.isSuccess()){
            resultBean.setMsg("删除失败！");
            return resultBean;
        }
        resultBean.setMsg("删除成功！");
        return resultBean;
    }

}